<template>
  <a-card :bordered="false">
    <a-spin tip="Loading..." :spinning="confirmLoading">
      <a-form-model
        :form="formData"
        ref="ruleForm"
        :model="formData"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :rules="rules"
      >
        <div class="title">流程基本信息</div>
        <a-form-model-item label="流程名称" prop="name">
          <a-input placeholder="请输入流程名称" v-model="formData.name" :disabled="isDetails" />
        </a-form-model-item>
        <a-form-model-item label="业务类型" prop="type">
          <j-dict-select-tag v-model="formData.type" dictCode="process_approval_type" placeholder="请选择业务类型" :disabled="isDetails" />
        </a-form-model-item>
        <a-form-model-item label="生效范围" prop="rangeList">
          <j-select-depart v-model="rangeList" :trigger-change="true" :multi="true" @rows="getSelectRows" :disabled="isDetails" />
        </a-form-model-item>
        <a-form-model-item label="流程说明" prop="remark">
          <a-textarea v-model="formData.remark" placeholder="请至少输入五个字符" :rows="4" allow-clear :disabled="isDetails" />
        </a-form-model-item>
        <div class="title">流程设置</div>
        <a-form-model-item :wrapper-col="{ span: 20, offset: 1 }" prop="nodeList">
          <process-figure
            ref="ProcessFigure"
            class="ProcessFigure"
            v-model="formData.nodeList"
            :showIcon="!isDetails"
            :showYey="isDetails"
            @fatherMethod="handleNode"
          >
            <template slot="rigth_content" slot-scope="{ scoped }">
              <div class="rigth_content" style="margin-left:10px;">
                <div class="lable">
                  审核人:
                  <div class="user">{{ scoped.approverName || scoped.approverRoleScopeName }}</div>
                </div>
              </div>
            </template>
          </process-figure>
          <a-button class="list add" block @click="handleNode(formData.nodeList.length + 1)" v-if="!isDetails">
            <a-icon type="plus" />添加
          </a-button>
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 14, offset: 2 }">
          <a-button type="primary" size="large" style="width: 90px;" @click="handleFlow" v-if="routeName == 'process-add' || routeName == 'process-edit-@id'" > 确定 </a-button>
          <a-button size="large" style="margin-left: 10px;width: 90px;" @click="resetForm" v-if="routeName == 'process-add'" > 重置 </a-button>
          <a-button size="large" style="margin-left: 10px;width: 90px;" @click="goBack" v-else> 返回 </a-button>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
    <add-node ref="nodeRef" @onChildValue="onChildValue" />
  </a-card>
</template>
<script>
import * as flowServiceApi from '@/api/plugging/flowService.js'
import addNode from './modules/addNode'
import ProcessFigure from './modules/processFigure'
var validateNodeList = (rule, value, callback) => {
  if (value && value.length >= 2) {
    callback()
  } else {
    callback('请设置至少添加流程两条节点信息')
  }
}
var nameValidator = (rule, value, callback) => {
  if (!value || new RegExp(/^.{2,50}$/).test(value)) {
    callback()
  } else {
    callback('请输入长度为2-50的流程名称')
  }
}
var remarkValidator = (rule, value, callback) => {
  if (!value || new RegExp(/^.{5,150}$/).test(value)) {
    callback()
  } else {
    callback('请输入长度为5-150的流程说明')
  }
}
export default {
  components: { addNode, ProcessFigure },
  computed: {
    routeName() {
      return this.$route.name
    },
    isDetails() {
      if(this.routeName==='process-details-@id') {
        return true
      } else {
        return false
      }
    }
  },
  inject:['closeCurrent'],
  data() {
    return {
      id: null,
      nodeBool: false,
      confirmLoading: false,
      typeOptions: [
        { text: '案事件', value: '1' },
        { text: '情报事件', value: '2' }
      ],
      labelCol: { span: 2 },
      wrapperCol: { span: 10 },
      rangeList: null, // 生效范围
      formData: {
        rangeList: [], //生效范围列表
        nodeList: [] //节点列表
      },
      rules: {
        type: [{ required: true, message: '请选择业务类型', trigger: 'change' }],
        name: [
          { required: true, message: '请填写流程名称', trigger: 'change' },
          { validator: nameValidator },
        ],
        remark: [
          { required: false, message: '请填写流程说明', trigger: 'change' },
          { validator: remarkValidator },
        ],
        rangeList: [{ required: true, type: 'array', message: '请选择生效范围', trigger: 'change' }],
        nodeList: [
          { required: true, type: 'array', message: '请设置流程节点', trigger: 'change' },
          // { validator: validateNodeList }
        ]
      }
    }
  },
  async created() {
    if (this.$route.params && Object.keys(this.$route.params).length > 0 && this.$route.params.id) {
      this.id = this.$route.params.id
      this.initForm()
    }
  },
  methods: {
    // 获取流程详情
    initForm() {
      flowServiceApi
        .getDetail(this.id)
        .then(res => {
          if (res.success) {
            this.formData = res.result
            this.$set(this.formData, 'id', this.id)
            // 生效范围
            if (this.formData && this.formData.rangeList) {
              this.rangeList = this.formData.rangeList.map(v => v.rangeId).join(',')
            }
            // 流程设置
            if(this.formData && !this.formData.nodeList) {
              this.$set(this.formData, 'nodeList', [])
            }
          } else {
            this.$message.warn(res.message)
          }
        })
        .catch(e => {
          this.$message.warn('请求失败！')
        })
    },
    getSelectRows(keys) {
      console.log("keys")
      console.log(keys)
      let rangeList = []
      if (keys && keys.length > 0) {
        rangeList = keys.map(item => {
          let obj = {}
          if (item && Object.keys(item).length > 0) {
            obj.rangeId = item.id
            obj.rangeName = item.title
            obj.type = 1
          }
          return obj
        })
      }
      this.$set(this.formData, 'rangeList', rangeList)
      this.$refs['ruleForm'].validateField('rangeList')
    },
    // //添加、编辑流程节点
    handleNode(count, record, handleType) {
      this.nodeBool = true
      this.$nextTick(() => {
        this.$refs.nodeRef.order = count
        if (record && Object.keys(record).length > 0) {
          this.$refs.nodeRef.edit(record, handleType)
        } else {
          this.$refs.nodeRef.add()
        }
      })
    },
    // 获取节点信息 handleType为add添加节点，handleType为edit编辑节点
    async onChildValue(handleType, val) {
      // console.log(val)
      if (val && Object.keys(val).length > 0) {
        if (handleType === 'add') {
          this.formData.nodeList.push(val)
        } else if (handleType === 'edit') {
          let columnsIndex = this.formData.nodeList.findIndex(item=> item.approvalLevel === val.approvalLevel)
          this.formData.nodeList.splice(columnsIndex, 1, val)
          // let item = this.formData.nodeList.find(obj => {
          //   return obj.approvalLevel == val.approvalLevel
          // })
          // item = Object.assign({}, item, val)
          // console.log(item, val)
          // item.approverId = val.approverId
          // item.approverName = val.approverName
          // item.nodeName = val.nodeName
          // item.userIds = val.userIds
        }
      }
      this.$nextTick(() => {
        this.nodeBool = false
      })
    },
    // //添加、编辑流程
    handleFlow() {
      let that = this
      let nodeList = this.formData.nodeList
      for (const key in nodeList) {
        nodeList[key].approvalLevel = Number(key) + 1
      }
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          try {
            let res
            that.confirmLoading = true
            if (this.routeName === 'process-add') {
              res = await flowServiceApi.addProcess(that.formData)
            } else {
              res = await flowServiceApi.updateProcess(that.formData)
            }
            if (res && res.success) {
              that.confirmLoading = false
              that.$message.success(res.message? res.message: `操作成功`)
              that.$router.push(`/process`)
              that.closeCurrent()
            } else {
              that.confirmLoading = false
              that.$message.error(res.message? res.message: `操作失败`)
            }
          } catch (err) {
            that.confirmLoading = false
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 重置
    resetForm() {
      this.formData = {}
      this.rangeList = null
      this.$set(this.formData, 'rangeList', [])
      this.$set(this.formData, 'nodeList', [])
    },
    // 返回
    goBack() {
      this.$router.push(`/process`)
      this.closeCurrent()
    }
  }
}
</script>
<style lang="less" scoped>
.title {
  // padding-left: 20px;
  box-sizing: border-box;
  border-width: 1px;
  border-bottom: 1px solid rgba(233, 233, 233, 1);
  border-radius: 2px;
  font-weight: 650;
  font-style: normal;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.847058823529412);
  line-height: 50px;
  font-size: 16px;
  margin-bottom: 30px;
  // border: 1px solid rgba(0, 0, 0, 0.85);
}
.list {
  display: flex;
  position: relative;
  justify-content: center;
  cursor: pointer;
  margin: 0 0 25px 0;
  align-items: center;
  width: 400px;
  height: 44px;
  background: inherit;
  box-sizing: border-box;
  border-width: 1px;
  border-style: solid;
  border-color: rgba(232, 232, 232, 1);
  border-radius: 4px;
  -moz-box-shadow: none;
  -webkit-box-shadow: none;
  box-shadow: none;
  font-family: 'Microsoft YaHei Regular', 'Microsoft YaHei';
  font-weight: 400;
  font-style: normal;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.8);
  line-height: 22px;
  i {
    padding-right: 10px;
  }
}
.ProcessFigure {
  // margin-left: 40px;
  /deep/.list {
    width: 400px;
  }
}
</style>
